package com.ren.config;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.ArrayList;

/**
 * 开机自启动管理器
 * 支持Windows、Linux和macOS平台的开机自启动功能
 */
public class AutoStartupManager {

    private static final String APP_NAME = "ScheduleManagement";
    private static final String JAR_NAME = "schedule_management.jar";

    /**
     * 启用开机自启动
     * @return 操作是否成功
     */
    public static boolean enableAutoStartup() {
        try {
            String os = getOS();
            switch (os) {
                case "windows":
                    return enableWindowsAutoStartup();
                case "linux":
                    return enableLinuxAutoStartup();
                case "mac":
                    return enableMacAutoStartup();
                default:
                    return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 禁用开机自启动
     * @return 操作是否成功
     */
    public static boolean disableAutoStartup() {
        try {
            String os = getOS();
            switch (os) {
                case "windows":
                    return disableWindowsAutoStartup();
                case "linux":
                    return disableLinuxAutoStartup();
                case "mac":
                    return disableMacAutoStartup();
                default:
                    return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 检查是否已设置开机自启动
     * @return 是否已设置开机自启动
     */
    public static boolean isAutoStartupEnabled() {
        try {
            String os = getOS();
            switch (os) {
                case "windows":
                    return isWindowsAutoStartupEnabled();
                case "linux":
                    return isLinuxAutoStartupEnabled();
                case "mac":
                    return isMacAutoStartupEnabled();
                default:
                    return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取当前操作系统类型
     * @return 操作系统类型 (windows/linux/mac)
     */
    private static String getOS() {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            return "windows";
        } else if (osName.contains("mac")) {
            return "mac";
        } else {
            return "linux";
        }
    }

    /**
     * 获取当前jar包的完整路径
     * @return jar包路径
     */
    private static String getJarPath() {
        try {
            return new File(AutoStartupManager.class.getProtectionDomain()
                    .getCodeSource().getLocation().toURI()).getPath();
        } catch (Exception e) {
            // 如果无法获取实际路径，则使用默认名称
            return JAR_NAME;
        }
    }

    // Windows平台实现
    private static boolean enableWindowsAutoStartup() {
        try {
            String jarPath = getJarPath();
            String cmd = "reg add HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run " +
                    "/v " + APP_NAME + " /t REG_SZ /d \"javaw -jar \\\"" + jarPath + "\\\"\" /f";
            Process process = Runtime.getRuntime().exec(cmd);
            return process.waitFor() == 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean disableWindowsAutoStartup() {
        try {
            String cmd = "reg delete HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run " +
                    "/v " + APP_NAME + " /f";
            Process process = Runtime.getRuntime().exec(cmd);
            return process.waitFor() == 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean isWindowsAutoStartupEnabled() {
        try {
            String cmd = "reg query HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run " +
                    "/v " + APP_NAME;
            Process process = Runtime.getRuntime().exec(cmd);
            return process.waitFor() == 0;
        } catch (Exception e) {
            return false;
        }
    }

    // Linux平台实现
    private static boolean enableLinuxAutoStartup() {
        try {
            String autostartDir = System.getProperty("user.home") + "/.config/autostart";
            String desktopFile = autostartDir + "/" + APP_NAME.toLowerCase() + ".desktop";

            // 创建目录
            Files.createDirectories(Paths.get(autostartDir));

            // 创建desktop文件内容
            List<String> lines = new ArrayList<>();
            lines.add("[Desktop Entry]");
            lines.add("Type=Application");
            lines.add("Name=" + APP_NAME);
            lines.add("Exec=java -jar \"" + getJarPath() + "\"");
            lines.add("Hidden=false");
            lines.add("NoDisplay=false");
            lines.add("X-GNOME-Autostart-enabled=true");

            // 写入文件
            Files.write(Paths.get(desktopFile), lines);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean disableLinuxAutoStartup() {
        try {
            String autostartDir = System.getProperty("user.home") + "/.config/autostart";
            String desktopFile = autostartDir + "/" + APP_NAME.toLowerCase() + ".desktop";
            Files.deleteIfExists(Paths.get(desktopFile));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean isLinuxAutoStartupEnabled() {
        try {
            String autostartDir = System.getProperty("user.home") + "/.config/autostart";
            String desktopFile = autostartDir + "/" + APP_NAME.toLowerCase() + ".desktop";
            return Files.exists(Paths.get(desktopFile));
        } catch (Exception e) {
            return false;
        }
    }

    // macOS平台实现
    private static boolean enableMacAutoStartup() {
        try {
            String plistFile = System.getProperty("user.home") +
                    "/Library/LaunchAgents/com.ren." + APP_NAME.toLowerCase() + ".plist";

            String jarPath = getJarPath();
            String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                    "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" " +
                    "\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" +
                    "<plist version=\"1.0\">\n" +
                    "<dict>\n" +
                    "    <key>Label</key>\n" +
                    "    <string>com.ren." + APP_NAME.toLowerCase() + "</string>\n" +
                    "    <key>ProgramArguments</key>\n" +
                    "    <array>\n" +
                    "        <string>java</string>\n" +
                    "        <string>-jar</string>\n" +
                    "        <string>" + jarPath + "</string>\n" +
                    "    </array>\n" +
                    "    <key>RunAtLoad</key>\n" +
                    "    <true/>\n" +
                    "</dict>\n" +
                    "</plist>";

            Files.createDirectories(Paths.get(System.getProperty("user.home") + "/Library/LaunchAgents"));
            Files.write(Paths.get(plistFile), content.getBytes());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean disableMacAutoStartup() {
        try {
            String plistFile = System.getProperty("user.home") +
                    "/Library/LaunchAgents/com.ren." + APP_NAME.toLowerCase() + ".plist";
            Files.deleteIfExists(Paths.get(plistFile));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean isMacAutoStartupEnabled() {
        try {
            String plistFile = System.getProperty("user.home") +
                    "/Library/LaunchAgents/com.ren." + APP_NAME.toLowerCase() + ".plist";
            return Files.exists(Paths.get(plistFile));
        } catch (Exception e) {
            return false;
        }
    }
}
